const jwt = require('jsonwebtoken');
const helper = require('../../util/helper');
const config = require('../../config/environment/index');
const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

exports.add = async (ctx) => {
    let project_name = ctx.request.body.project_name ? ctx.request.body.project_name.trim() : '';
    let address = ctx.request.body.address || '';
    let landAgent_id = ctx.request.body.landAgent_id || 0;
    let remark = ctx.request.body.remark || '';
    let create_user_id = ctx.user.id || '';
    try {
        if (project_name === '' || address === '' || parseInt(landAgent_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        let existLandAgent = await mysql.query(`SELECT * FROM landagent WHERE landAgent_id = ?`, landAgent_id);
        if (existLandAgent.length <= 0) {
            ctx.body = {
                result: 203,
                message: "找不到房开商"
            };
            return
        }
        let existProjects = await mysql.query(`SELECT * FROM project WHERE project_name = ? and is_deleted = 0 `, project_name);
        if (existProjects.length > 0) {
            ctx.body = {
                result: 204,
                message: "已存在重名项目"
            };
            return
        }
        existLandAgent[0].proj_numb++;
        let newProject = {
            project_name,
            address,
            landAgent_id,
            remark,
            create_user_id,
            status: 0,
            is_deleted: 0,
            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        };
        await new Promise((resolve, reject) => {
            var trans = mysql.Client.startTransaction();
            trans.query(`INSERT INTO project SET ?`, newProject, function (err, info) {
                if (err) {
                    trans.rollback();
                    ctx.body = {
                        result: 202,
                        message: "新增项目失败"
                    };
                    resolve(ctx);
                } else {
                    trans.query(`UPDATE landagent SET ? WHERE landagent_id = ? `, [existLandAgent[0], landAgent_id], function (err) {
                        if (err) {
                            trans.rollback();
                            ctx.body = {
                                result: 202,
                                message: "新增项目失败"
                            };
                        } else {
                            trans.commit();
                            ctx.body = {
                                result: 200,
                                id: info.insertId,
                                message: "新增项目成功"
                            };
                        }
                        resolve(ctx);
                    });
                }
            });
            trans.execute();
        });
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.delete = async (ctx) => {
    let project_id = ctx.params.project_id || 0;
    try {
        if (parseInt(project_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return
        }
        let existProjects = await mysql.query(`SELECT * FROM project WHERE project_id = ? and is_deleted = 0 `, project_id);
        if (existProjects.length <= 0) {
            ctx.body = {
                result: 202,
                message: "对象不存在或已删除"
            };
        } else {
            existProjects[0].update_time = moment().format('YYYY-MM-DD HH:mm:ss');
            existProjects[0].is_deleted = 1;
            let existLandAgent = await mysql.query(`SELECT * FROM landagent WHERE landAgent_id = ?`, existProjects[0].landAgent_id);
            if (existLandAgent.length <= 0) {
                await mysql.query(`update project set ? WHERE project_id = ? `, [existProjects[0], project_id]);
                ctx.body = {
                    result: 200,
                    message: "删除成功"
                };
            } else {
                existLandAgent[0].proj_numb--;
                await new Promise((resolve, reject) => {
                    var trans = mysql.Client.startTransaction();
                    trans.query(`UPDATE landagent SET ? WHERE landagent_id = ? `, [existLandAgent[0], existLandAgent[0].landAgent_id], function (err, info) {
                        if (err) {
                            trans.rollback();
                            ctx.body = {
                                result: 203,
                                message: "删除失败"
                            };
                            resolve(ctx);
                        } else {
                            trans.query(`update project set ? WHERE project_id = ? `, [existProjects[0], project_id], function (err) {
                                if (err) {
                                    trans.rollback();
                                    ctx.body = {
                                        result: 202,
                                        message: "对象不存在或已删除"
                                    };
                                } else {
                                    trans.commit();
                                    ctx.body = {
                                        result: 200,
                                        message: "删除成功"
                                    };
                                }
                                resolve(ctx);
                            });
                        }
                    });
                    trans.execute();
                });
            }
        }
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.update = async (ctx) => {
    let project_id = ctx.request.body.project_id || 0;
    let project_name = ctx.request.body.project_name ? ctx.request.body.project_name.trim() : '';
    let address = ctx.request.body.address || '';
    let landAgent_id = ctx.request.body.landAgent_id || 0;
    let remark = ctx.request.body.remark || '';
    let status = ctx.request.body.status || 0;
    try {
        if (parseInt(project_id) <= 0 || project_name === '' || address === '' || parseInt(landAgent_id) <= 0 || parseInt(status) < 0) {
            ctx.body = {
                result: 201,
                message: "请检查参数"
            };
            return;
        }
        let existLandAgent = await mysql.query(`SELECT * FROM landagent WHERE landAgent_id = ?`, landAgent_id);
        if (existLandAgent.length <= 0) {
            ctx.body = {
                result: 203,
                message: "找不到房开商"
            };
            return
        }
        let existProjects = await mysql.query(`SELECT * FROM project WHERE project_name = ? and is_deleted = 0 and project_id <> ? `, [project_name,project_id]);
        if (existProjects.length > 0) {
            ctx.body = {
                result: 204,
                message: "已存在重名项目"
            };
            return
        }
        let selectProject = await mysql.query(`SELECT * FROM project WHERE project_id = ? and is_deleted = 0 `, [project_id]);
        if (selectProject.length > 0) {
            // console.log('selectProject:', selectProject);
            selectProject[0].project_name = project_name;
            selectProject[0].landAgent_id = landAgent_id;
            selectProject[0].address = address;
            selectProject[0].remark = remark;
            selectProject[0].status = status;
            selectProject[0].update_time = moment().format('YYYY-MM-DD HH:mm:ss');
            ret = await mysql.query(`UPDATE project SET ? WHERE project_id = ?`, [selectProject[0], selectProject[0].project_id]);
            if (!ret || ret.insertId === -1) {
                ctx.body = {
                    result: 202,
                    message: "更新项目失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "更新项目成功"
                };
            }
        } else {
            ctx.body = {
                result: 203,
                message: "项目不存在或者已删除"
            };
        }
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.getList = async (ctx) => {
    let create_user_id = ctx.user.id || '';
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let keyword = ctx.query.keyword ? ctx.query.keyword.trim() : '';

    try {
        let needColumn = ' v_project_detail.project_id,v_project_detail.project_name,v_project_detail.create_time,v_project_detail.update_time,v_project_detail.create_user_id,v_project_detail.address,v_project_detail.landAgent_name,v_project_detail.remark,v_project_detail.status ';
        let results = (keyword === '') ?
            await mysql.query(`SELECT ` + needColumn + ` FROM v_project_detail WHERE is_deleted = 0 ORDER BY project_id DESC LIMIT ${indexfrom}, ${counts}`)
            : await mysql.query(`SELECT ` + needColumn + ` FROM v_project_detail WHERE is_deleted = 0 and project_name like ? or address like ? ORDER BY project_id DESC LIMIT ${indexfrom}, ${counts}`, ['%' + keyword + '%','%' + keyword + '%']);
        let totalResult = (keyword === '') ? await mysql.query(`SELECT COUNT(project_id) AS total FROM v_project_detail WHERE is_deleted = 0`, create_user_id)
            : await mysql.query(`SELECT COUNT(project_id) AS total FROM v_project_detail WHERE is_deleted = 0 and project_name like ? or address like ? `, ['%' + keyword + '%','%' + keyword + '%']);
        ctx.body = {
            result: 200,
            list: results,
            totalpage: Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0) / counts),
            totalcounts: totalResult.length > 0 ? totalResult[0].total : 0,
            message: "查询成功"
        };
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.getDetail = async (ctx) => {
    let project_id = ctx.params.project_id || 0;
    try {
        if (parseInt(project_id) <= 0) {
            ctx.body = {
                result: 201,
                message: "无效的项目id"
            };
            return;
        }
        let needColumn = ' v_project_detail.project_id,v_project_detail.project_name,v_project_detail.create_time,v_project_detail.update_time,v_project_detail.proj_numb,v_project_detail.note ';
        let results = await mysql.query(`SELECT` + needColumn + `FROM v_project_detail WHERE project_id = ? and is_deleted = 0`, [project_id]);
        if (results.length > 0) {
            ctx.body = {
                result: 200,
                resultInfo: results[0],
                message: "查询成功"
            };
        } else {
            ctx.body = {
                result: 203,
                message: "查询失败"
            };
        }
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}




